package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;


    /**
     * 添加套餐
     */
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("套餐添加：{}",setmealDto);

        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }


    /**
     * 分页查询套餐
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        //创建分页构造器对象
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage =new Page<>();

        //创建查询条件容器进行查询
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //添加模糊查询条件
        lqw.like( name != null,Setmeal::getName,name);
        //添加排序条件(根据修改的时间降序排列)
        lqw.orderByAsc(Setmeal::getUpdateTime);

        setmealService.page(pageInfo,lqw);

        //对象拷贝（拷贝除数据外的所有配置,数据需封装为setmealDto格式）
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");

        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item) -> {
            //创建seteamlDTO对象准备接收数据
            SetmealDto setmealDto = new SetmealDto();
            //拷贝数据
            BeanUtils.copyProperties(item, setmealDto);
            //获取菜品分类数据
            Category byId = categoryService.getById(setmealDto.getCategoryId());
            //判断数据是否为空
            if (byId != null) {
                setmealDto.setCategoryName(byId.getName());
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);

        return R.success(dtoPage);
    }


    /**
     * 删除套餐
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);

        setmealService.removeWithDish(ids);

        return R.success("删除成功");
    }

    /**
     * 停售/启售
     */
    @PostMapping("/status/{id}")
    public R<String> updated(@RequestParam List<Long> ids){
        for (Long id : ids) {
            Setmeal byId = setmealService.getById(id);
            if (byId.getStatus() != 0 ) {
                byId.setStatus(0);
            }else {
                byId.setStatus(1);
            }
            //将修改后的数据写回
            setmealService.updateById(byId);
        }

        return R.success("修改成功");
    }


    /**
     * 查询套餐
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getSetmealDto(@PathVariable Long id){
        //

        SetmealDto setmealDto = setmealService.getWithCategoryWithSetmealDish(id);

        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        log.info("套餐数据：{}",setmealDto);

        //TODO 调用service层中构造的方法
        setmealService.updateWithCategoryWithSermealDish(setmealDto);

        return R.success("修改成功");
    }

    /**
     * 根据条件查询分类
     */
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        //创建条件查询器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //添加条件
        lqw.eq(setmeal.getCategoryId() != null , Setmeal::getCategoryId,setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus() != null , Setmeal::getStatus,1);
        //添加排序条件，先按sort进行排序，再按修改时间进行排序
        lqw.orderByAsc(Setmeal::getCode).orderByDesc(Setmeal::getUpdateTime);

        //进行查询
        List<Setmeal> list = setmealService.list(lqw);
        return R.success(list);
    }


}
